package com.dkm.orproject.dkmoa.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dkm.orproject.dkmoa.domain.OaLog;
import com.dkm.orproject.dkmoa.domain.OaPersonnel;
import com.dkm.orproject.dkmoa.domain.OaRegimeType;
import com.dkm.orproject.dkmoa.service.OaRegimeTypeService;
import com.dkm.orproject.utils.jwt.login.UserLoginToken;
import com.dkm.orproject.utils.utils.ThreeVo;
import com.dkm.orproject.utils.utils.Tools;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *  @ClassName : OaRegimeTypeAction  //类名
 *  @Description : 规章制度类型控制层
 *  @Author : zmh //作者
 *  @Date: 2020-11-12 09:28  //时间
 */
@RestController
@RequestMapping("/OaRegimeTypeAction")
public class OaRegimeTypeAction {
    /**
     * 工具类
     */
    @Resource
    Tools tools;

    /**
     * 登陆人
     */
    OaPersonnel personnel;


    /**
     * 日志
     */
    OaLog log;

    /**
     * 回调map
     */
    Map<String, Object> map;
    /**
     * 规则制度类型服务接口
     */
    @Resource
    private OaRegimeTypeService oaRegimeTypeService;

    /**
     * 通过id查询规则制度regimeType信息
     * @param pkRegimeTypeId 该规则制度regimeType的id值
     * @param request  服务器请求
     * @return 返回规章制度对象regime存入map
     */
    @GetMapping("findById/{pkRegimeTypeId}")
    @UserLoginToken
    public Map<String, Object> selectByPrimaryKey(@PathVariable("pkRegimeTypeId") Long pkRegimeTypeId, HttpServletRequest request) {
        OaPersonnel oaPersonnel = (OaPersonnel) request.getSession().getAttribute("user");
        Map<String, Object> map = new HashMap<>();
        try {
            OaRegimeType regime = oaRegimeTypeService.selectByPrimaryKey(pkRegimeTypeId);
            OaLog log = new OaLog();
            log.setLogTitle("规章制度类型id查询模块查询成功");
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            log.setLogIp(request.getRemoteAddr());
            log.setLogType("1");
            log.setLogBody(JSON.toJSON(oaPersonnel).toString());
            tools.rowMap(map, 1, null);
            map.put("data", regime);
            return map;
        } catch (Exception e) {
            addErrorLog(request,"规章制度类型根据id查询模块异常",e);
        }
        return map;
    }

    /**
     * 根据id删除一条规章制度类型信息
     * @param pkRegimeTypeId 规章制度类型的id值
     * @param session 会话
     * @param request 服务器请求
     * @return 回调函数
     */
    @UserLoginToken
    @DeleteMapping("deleteRegimeTypeById/{pkRegimeTypeId}")
    public Map<String, Object> deleteByPrimaryKey(@PathVariable("pkRegimeTypeId") Long pkRegimeTypeId, HttpSession session, HttpServletRequest request) {
        OaPersonnel oaPersonnel = (OaPersonnel) session.getAttribute("user");
        Map<String, Object> map = new HashMap<>(16);
        try {
            OaLog log = new OaLog();
            OaRegimeType oaRegimeType = new OaRegimeType();
            oaRegimeType.setPkRegimeTypeId(pkRegimeTypeId);
            oaRegimeType.setIsRevision("0");
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            log.setLogTitle("规章制度类型的删除模块");
            int rows = oaRegimeTypeService.deleteByPrimaryKey(pkRegimeTypeId);
            log.setLogIp(request.getRemoteAddr());
            log.setLogType("1");
            log.setLogBody(JSON.toJSON(oaPersonnel).toString());
            tools.rowMap(map, rows, log);
            return map;
        } catch (Exception e) {
            addErrorLog(request,"规章制度类型的删除模块异常",e);
            return map;
        }


    }

    /**
     * 分页查询所有规章制度类型的信息
     * @param oaRegimeType 规则制度类型模型
     * @param page  当前页数
     * @param limit  显示的行数
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param request 请求对象
     * @return
     */
    @UserLoginToken
    @GetMapping("selectAll")
    public Map<String,Object> findAll(OaRegimeType oaRegimeType, Integer page, Integer limit, String startTime, String endTime, HttpServletRequest request){
        try {
            //查询总行数
            Long rowCount=oaRegimeTypeService.rowCount(oaRegimeType,startTime,endTime);
            //分页查询集合
            List<OaRegimeType> logs=oaRegimeTypeService.selectAll(oaRegimeType,startTime,endTime,page,limit);
            //返回集合
            return Tools.maps(logs,rowCount);
        } catch (Exception e) {
            addErrorLog(request,"查询规章制度类型的所有方法",e);
            return map;
        }
    }

    /**
     * 批量删除规则制度类型
     * @param ids 删除的条数的id[数组
     * @param session 从session中获得user对象
     * @param request 请求对象
     * @return
     */
    @DeleteMapping("deleteAll")
    @UserLoginToken
    public Map<String, Object> deleteAll(@RequestParam(value = "ids[]", required = false) Long[] ids, HttpSession session, HttpServletRequest request) {
        OaPersonnel user = (OaPersonnel) session.getAttribute("user");
        List<Long> list;
        Map<String,Object> map=new HashMap<>();
        if (ObjectUtils.isEmpty(ids)){
            return tools.rowMap(map,0,null);
        }else {
            list= Arrays.asList(ids);
        }
        try {
            OaLog log = new OaLog();
            int deleteAll = oaRegimeTypeService.deleteAll(list);
            log.setLogType("1");
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(JSONObject.toJSON(user).toString());
            log.setLogTitle("规章制度类型批量删除模块");
            log.setCreatedBy(user.getPersonnelName());
            tools.rowMap(map, deleteAll, log);
            map.put("data",deleteAll);
            return map;
        } catch (Exception e) {
            addErrorLog(request,"规章制度类型删除模块异常",e);
            return map;
        }

    }

    /**
     * 增加规则制度类型和修改规则制度类型
     * @param oaRegimeType 规章制度类型对象
     * @param request  请求对象
     * @return map 中存入了增加和修改成功的条数
     */
    @PostMapping("updateOrAdd")
    @UserLoginToken
    public Map<String, Object> add(OaRegimeType oaRegimeType, HttpServletRequest request) {
        OaPersonnel oaPersonnel = (OaPersonnel) request.getSession().getAttribute("user");
        Map<String, Object> map = new HashMap<>();
        if (ObjectUtils.isEmpty(oaPersonnel)) {
            tools.rowMap(map, 0, null);
        }
        try {
            int rows = 0;
            OaLog log = new OaLog();
            //如果id不为空 那么就修改 否则增加
            if (oaRegimeType.getPkRegimeTypeId() != null && !"".equals(oaRegimeType.getPkRegimeTypeId())) {
                rows = oaRegimeTypeService.updateByPrimaryKeySelective(oaRegimeType,oaPersonnel.getPersonnelName());
            } else {
                oaRegimeType.setCreatedBy(oaPersonnel.getPersonnelName());
                oaRegimeType.setIsRevision("1");
                if(oaRegimeType.getRegimgTypeSuperior()==null) {
                    oaRegimeType.setRegimgTypeSuperior(0L);
                }
                log.setLogTitle("规章制度类型增加模块");
                rows = oaRegimeTypeService.insertSelective(oaRegimeType,oaPersonnel.getPersonnelName());
            }
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(JSONObject.toJSON(oaPersonnel).toString());
            log.setLogType("1");
            tools.rowMap(map, rows, log);
            return map;
        } catch (Exception e) {
            addErrorLog(request,"规章制度类型增加或修改模块异常",e);
        }
        return map;
    }


    @UserLoginToken
    @GetMapping("loadOaRegimeType")
    public List<ThreeVo> loadClientType(Long id, String show, HttpServletRequest request){
        //获取当前人操作信息
        rowMap(request);
        //判断操作人是否存在
        if (ObjectUtils.isEmpty(personnel)){
            return null;
        }
        try {
            return oaRegimeTypeService.loadOaRegimeType(id,show);
        }catch (Exception e){
            addErrorLog(request,"客户类型查询所有",e);
        }
        return null;
    }

    /**
     * 收集报错日志
     *
     * @param request 请求 用于得到当前登录人和ip地址
     * @param title   模块标题
     * @param e       异常参数
     */
    private void addErrorLog(HttpServletRequest request, String title, Exception e) {
        //后台打印报错信息
        e.printStackTrace();
        //获取当前操作人
        personnel = (OaPersonnel) request.getSession().getAttribute("user");
        //新建日志
        log = new OaLog();
        //日志类型
        log.setLogType("0");
        //日志内容
        log.setLogBody(e.getLocalizedMessage());
        //日志标题
        log.setLogTitle(title);
        //请求地址
        log.setLogIp(request.getRemoteAddr());
        //判断当前登陆人是否存在
        if (ObjectUtils.isEmpty(personnel)) {
            //当前操作人名称
            log.setCreatedBy(personnel.getPersonnelName());
        }
        //存入报错日志
        tools.errorMap(log);
    }


    /**
     * 优化代码 获取当前登陆人信息
     *
     * @param request 服务器请求
     */
    private void rowMap(HttpServletRequest request) {
        //新建返回Map模型
        map = new HashMap<>(16);
        //获取登陆人信息
        personnel = (OaPersonnel) request.getSession().getAttribute("user");
        //为空则清空map
        if (ObjectUtils.isEmpty(personnel)) {
            return;
        }
        //新建日志
        log = new OaLog();
        //得到ip
        log.setLogIp(request.getRemoteAddr());
        //登陆人名称
        log.setCreatedBy(personnel.getPersonnelName());
    }

    /**
     * 日期格式化
     *
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // true:允许输入空值，false:不能为空值
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}
